//
//  DKTabBarViewController.swift
//  Sina
//
//  Created by  duan on 16/4/6.
//  Copyright © 2016年 duan. All rights reserved.
//

import UIKit

class DKTabBarViewController: UITabBarController {

    //懒加载按钮
    lazy private var btn: UIButton = UIButton(imageName: "tabbar_compose_icon_add", BackImageName: "tabbar_compose_button")
    
    //点击事件 private是私有的,当运行循环搜索点击事件时会找不到这个方法,需要加上
    @objc private func writeBtnClick (){
    
    print("点我了")
    
    }
    
    
    //MARK:- 视图将要加载是调用的方法
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //将按钮放到最上面:
        tabBar.bringSubviewToFront(btn) //不能放到viewdidload方法中,因为下面的tabBar也是懒加载的,按钮就会被放到下面

    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tabBar.tintColor = UIColor.orangeColor()

        //首页:
        addChildViewControllers(DKHomeTableViewController(), name: "首页", imageString: "tabbar_home")
        //消息:
        addChildViewControllers(DKMessageTableViewController(), name: "消息", imageString: "tabbar_message_center")
        
        //添加一个空的控制器,用于给撰写按钮腾出位置:
        addChildViewController(UIViewController())
        
        
        //发现:
        addChildViewControllers(DKDiscoverTableViewController(), name: "发现", imageString: "tabbar_discover")
        //我的:
        addChildViewControllers(DKMineTableViewController(), name: "我的", imageString: "tabbar_profile")
        
        
        
//        //创建按钮:
            setButton()
        
        
        
    }
    
  
    
    
    

}

//MARK: - 设置界面:
extension DKTabBarViewController{
    
    //添加子控件的方法:
    private func addChildViewControllers(ViewController: UIViewController, name: String, imageString: String){
        ViewController.title  = name
        ViewController.tabBarItem.image = UIImage(named: imageString)

        addChildViewController(ViewController)
    }
    
    private func setButton(){
        tabBar.addSubview(btn)
        
        //获取tabBar的个数:
        let numTabBar: Int = childViewControllers.count
        //计算每一个tabBar的宽度:)
        let w = tabBar.bounds.width/CGFloat(numTabBar) - 2
        //按钮的宽度有点小,-2 就可以让宽度变长,
        
        print(numTabBar)
        
        btn.frame = CGRectInset(tabBar.bounds, w * 2, 0)
        
        //按钮注册点击事件:
        btn.addTarget(self, action: "writeBtnClick", forControlEvents: .TouchUpInside)

    
    }
}

